/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.config
{
	/**
	 * Simple parser for INI files
	 * Supports nested sections and the special "global" section.
	 * This parser also supports the localization file format
	 * 
	 * This class doesn't do any error handling to keep things simple
	 */
	
	public final class INIParser
	{
		private static const GLOBAL_SECTION:String = 'global';
		private static const SECTION_START:String = '[';
		private static const SECTION_END:String = ']';
		private static const NESTED_SECTION:String = '.';
		
		private static const COMMENT:String = ';';
		private static const COMMENT_2:String = '#';
		private static const EMPTY:String = '';

		private static const NEW_LINE:RegExp = /\r?\n/;
		private static const KEY_SEPARATOR:RegExp = / ?= ?/;
		
		public function INIParser()
		{
		}
		
		public function convert(code:String):Object
		{
			var data:Object = {};
			var holder:Object = data;

			for each (var line:String in code.split(NEW_LINE))
			{
				switch (line.charAt(0))
				{
					case EMPTY:
					case COMMENT:
					case COMMENT_2: break;
					case SECTION_START:
						var section:String = line.slice(1, line.indexOf(SECTION_END));
						holder = data;

						if (section !== GLOBAL_SECTION)
							for each (var part:String in section.split(NESTED_SECTION))
								holder = holder[part] || (holder[part] = {});
					break;
					default:
						var i:int = line.search(KEY_SEPARATOR);
						holder[line.slice(0, i)] = Evaluator.parse(line.slice(i+1));
					break;
				}
			}
			return data;
		}
	}
}